/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import constants from './constants';

const win = window.top != window.self ? window.self : window;

function formateStorageKey(key) {
  const storageAccountTag = win.storageAccountTag || '';
  const k = (constants.STORAGE_PREFIX
    ? `${constants.STORAGE_PREFIX}_${key}`
    : ''
  ).toLocaleUpperCase();
  if (storageAccountTag && key.startsWith('a_')) {
    return `${k}_${storageAccountTag}`;
  }
  return k;
}

/**
 *
 * @description 设置缓存
 * @param opts
 * @returns
 */
export function setStorageSync(key, data, type = 'local') {
  try {
    const valueData = { data, ts: new Date().getTime() };
    const value = JSON.stringify(valueData);
    win[`${type}Storage`].setItem(formateStorageKey(key), value);
    return valueData;
  } catch (error) {
    return { error };
  }
}
export function setStorage(opts) {
  const { data, key, type } = opts;
  return new Promise(resolve => resolve(setStorageSync(key, data, type)));
}

/**
 *
 * @description 获取缓存
 * @param opts
 * @returns
 */
export function getStorageSync(key, type = 'local') {
  try {
    const value = win[`${type}Storage`].getItem(formateStorageKey(key));
    const valueData = value ? JSON.parse(value) : value;
    return {
      data: null,
      ...valueData,
    };
  } catch (error) {
    return { error };
  }
}
export function getStorage(opts) {
  const { key, type } = opts;
  return new Promise(resolve => resolve(getStorageSync(key, type)));
}

/**
 *
 * @description 移除缓存
 * @param opts
 * @returns
 */
export function removeStorageSync(key, type = 'local') {
  try {
    win[`${type}Storage`].removeItem(formateStorageKey(key));
    // eslint-disable-next-line no-empty
  } catch (error) {}
}
export function removeStorage(opts) {
  const { key, type } = opts;
  return new Promise(resolve => {
    removeStorageSync(key, type);
    resolve(opts);
  });
}
